package com.ruoyi.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;



import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author kaka.huang
 * @for study
 */
@Component
public class FileUpLoadUtil {
    // 上传文件到阿里云 OSS
    @Value("${aliyun.oss.endpoint}")
    public  String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    public  String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    public  String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    public  String bucketName;

    @Value("${aliyun.oss.fileUploadDir}")
    public  String fileUploadDir;

//    图片上传
    public  String uploadFileToOSS(byte[] fileBytes, String gameId ,String certificate) throws IOException {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建字节流输入流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);

            // 设置文件名，可以使用文本内容生成唯一文件名，避免重名
            String objectName = "audio/" + gameId.hashCode() + ".jpg";

            // 构造上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, byteArrayInputStream);

//            // 若存在旧文件，就先删除
//            if(certificate != null){
//                int lastSlashIndex = certificate.lastIndexOf("/");
//
//                int secondLastSlashIndex = certificate.lastIndexOf("/", lastSlashIndex - 1);
//                // 从倒数第二个斜杠的位置开始截取字符串
//                String OldName = certificate.substring(secondLastSlashIndex + 1);
//                System.out.println(OldName);
//                ossClient.deleteObject(bucketName,objectName);
//            }

            // 上传文件
            ossClient.putObject(putObjectRequest);
            System.out.println("File uploaded successfully to OSS.");

            // 去掉 endpoint 中的 https:// 前缀，确保不会重复添加
            String fileUrl = "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + objectName;

            return fileUrl;

        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("Error uploading file to OSS: " + e.getMessage());
        } finally {
            // 关闭 OSSClient
            ossClient.shutdown();
        }
    }

}
